package org.ithasu.tools.multimedia;

import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ithasu.tools.Console;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.ResultParser;
import com.google.zxing.common.HybridBinarizer;

public class BarCode {

	protected BarCode() {
	}

	// --- Read barcode ----------------------------------------

	public static Result read(BufferedImage image) {
		try {
			BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
			Map<DecodeHintType, List<?>> hints = new HashMap<>();
			hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.QR_CODE));
			Result result = new MultiFormatReader().decode(bitmap);
			return result;
		} catch (NotFoundException e) {
			// Just found nothing
			return null;
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}

	public static void debug(Result result) {
		if (result == null) {
			Console.message("No result");
		} else {
			ParsedResult parsedResult = ResultParser.parseResult(result);
			Console.message("(format: " + result.getBarcodeFormat() + ", type: " + parsedResult.getType()
					+ "):\nRaw result:\n" + result.getText() + "\nParsed result:\n" + parsedResult.getDisplayResult());
		}
	}
}
